<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片角色视图 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="['bdtop', i1 === 0 ? 'bdbottom' : '', 'v-center']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 == 0 ? '' : 'bdtop', 'v-center']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini"
              >删除</el-button
            >
            <el-button type="warning" @click="showSetRightDialog(scope.row)" icon="el-icon-setting" size="mini"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 设置权限对话框 -->

    <el-dialog
      title="提示"
      :visible.sync="setRightDialogVisible"
      width="50%"
    >
      <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id"
        default-expand-all
        :default-checked-keys="defaultKeys"
        ref="treeRef"
      >

      </el-tree>


      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getRoleList();
  },
  data() {
    return {
        //绑定树形组件
        treeProps: {
            children: 'children',
            label: 'authName'
        },

      roleList: [],
      rightList: [],
      setRightDialogVisible: false,
      // 设置默认勾选上的选项
      defaultKeys: [],
      roleId: ''
    };
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");

      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败!");
      }

      this.roleList = res.data;

      console.log(this.roleList);
    },

    removeRightById(role, rightId) {
      this.$confirm("此操作将删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );

          if (res.meta.status !== 200) {
            return this.$message.error("删除数据失败!");
          }

          this.$message({
            type: "success",
            message: "删除成功!"
          });

          role.children = res.data;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    async showSetRightDialog(role){
       
        this.roleId = role.id;
        const { data : res } = await this.$http.get('rights/tree')

        if (res.meta.status !== 200)
        {
            return this.$message.error('获取权限数据失败')
        }

        this.rightList = res.data

        console.log(this.rightList)
        
        this.defaultKeys = []

        this.getLeafKeys(role,this.defaultKeys)

        this.setRightDialogVisible = true

    },

    getLeafKeys(node,arr){

        if (!node.children)
        {
            return arr.push(node.id)
        }

        node.children.forEach(item => {
            this.getLeafKeys(item,arr) 
        });
    },

    async allotRights(){
        // 获得当前选中和半选中的Id
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      // join() 方法用于把数组中的所有元素放入一个字符串
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) { return this.$message.error('分配权限失败！') }
      this.$message.success('分配权限成功!')
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  }
};
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border: 1px solid #eee;
}
.bdbottom {
  border: 1px solid #eee;
}

.v-center {
  display: flex;
  align-items: center;
}
</style>
